<?php

namespace app\api\middleware;
use support\exception\ValidateException;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use utils\Jwt;


class JwtAuth implements MiddlewareInterface
{
	
    public function process(Request $request, callable $handler) : Response
    {	
		$token = $request->header('Authorization');
		if(!$token){
			return json(['status'=>411,'msg'=>'token不能为空']);
		}
		$jwt = Jwt::getInstance();
		$jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))->setSecrect(config('my.jwt_secrect'))->setToken($token);
		
		try{
			if($jwt->validationToken()){
				$info = json_decode($jwt->decode(),true);
				if($info){
					foreach($info as $k=>$v){
						$request->$k = $v;
					}
				}
				return $handler($request);
			}
		}catch(\Exception $e){
			return json(["status"=>$e->getCode(),"msg"=>$e->getMessage()]);
		}
    }
} 